package com.study.sqlSession;

import com.study.pojo.Configuration;

import java.util.List;


public class SqlSessionImpl implements SqlSession {

    private Configuration configuration;
    public SqlSessionImpl(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object  param) throws Exception {
        Executor executor = new ExecutorImpl();
        List<E> list = executor.query(configuration, configuration.getMappedStatementMap().get(statementId), param);
        return list;
    }

    @Override
    public <T> T selectOne(String statementId, Object  param) throws Exception {
        List<Object> list = selectList(statementId, param);
        if (list != null && list.size() == 1) {
            return (T) list.get(0);
        } else {
            throw new RuntimeException("查询结果为空或查询出多个结果");
        }
    }

    @Override
    public int insert(String statementId, Object param) throws Exception {
        return update(statementId, param);
    }

    @Override
    public int update(String statementId, Object param) throws Exception {
        Executor executor = new ExecutorImpl();
        return executor.update(configuration, configuration.getMappedStatementMap().get(statementId), param);

    }

    @Override
    public int delete(String statementId, Object  param) throws Exception {
        return update(statementId, param);
    }


    @Override
    public <T> T getMapper(Class<T> type) throws Exception {
        // 使用jdk动态代理生成Dao接口代理对象
        return configuration.getMapper(type, this);
    }

}
